package role

import (
	"errors"
	"fmt"
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/controller/admin"
	"yunj/pkg/yunj/app/enum/stateenum"
	"yunj/pkg/yunj/app/model"
	"yunj/pkg/yunj/app/service/admin/roleservice"
	"yunj/pkg/yunj/core/builder"
	"yunj/pkg/yunj/core/builder/builderconsts"
	"yunj/pkg/yunj/core/builder/builderdto"
	"yunj/pkg/yunj/core/builder/form/button"
	"yunj/pkg/yunj/core/builder/form/field"
	"yunj/pkg/yunj/core/db"
	"yunj/pkg/yunj/core/response"

	"github.com/gin-gonic/gin"
)

// 岗位管理
type Role struct {
	admin.Controller
}

// 列表
func (ctrl *Role) List(ctx *gin.Context) {
	ctrl.RenderTable(ctx, roleservice.RolePage.ListBuilder(ctx))
}

// 添加
func (ctrl *Role) Add(ctx *gin.Context) {
	ctrl.RenderForm(ctx, roleservice.RolePage.FormBuilder(ctx, false))
}

// 编辑
func (ctrl *Role) Edit(ctx *gin.Context) {
	ctrl.RenderForm(ctx, roleservice.RolePage.FormBuilder(ctx, true))
}

// 排序
func (ctrl *Role) Sort(ctx *gin.Context) {
	formBuilder := builder.NewForm(ctx, "RoleSort").
		Field(field.NewTreeEdit("sort_tree", "排序").SetSort(builderconsts.FORM_TREE_SORT_LEVEL)).
		Button(button.NewReset(), button.NewSubmit()).
		Load(func(f *builder.Form) (res any, err error) {
			query := global.MySQL.Where("state = ?", stateenum.NORMAL).Order("sort asc")
			var roles []model.AdminRole
			if err = query.Select("id", "name", "code").Find(&roles).Error; err != nil {
				err = fmt.Errorf("数据查询异常！%v", err)
				return
			}
			items := make([]*builderdto.FormTreeEditNode, 0, len(roles))
			for _, role := range roles {
				name := role.Name
				if role.Code != "" {
					name += fmt.Sprintf("(%s)", role.Code)
				}
				items = append(items, &builderdto.FormTreeEditNode{
					Id:   role.Id,
					Pid:  0,
					Name: name,
				})
			}
			res = map[string]any{
				"sort_tree": items,
			}
			return
		}).
		Submit(func(f *builder.Form, values map[string]any) (res builderdto.FormSubmitResult, err error) {
			sortTreeRaw, exists := values["sort_tree"]
			if !exists {
				err = errors.New("提交数据异常！")
				return
			}
			sortTree, ok := sortTreeRaw.([]any)
			if !ok {
				err = errors.New("提交数据错误！")
				return
			}
			sort := 0
			datas := []map[string]any{}
			for _, itemRaw := range sortTree {
				item, ok := itemRaw.(map[string]any)
				if !ok {
					continue
				}
				id, exists := item["id"]
				if !exists {
					continue
				}
				datas = append(datas, map[string]any{
					"id":   id,
					"sort": sort,
				})
				sort++
			}
			if len(datas) > 0 {
				err = db.Model(&model.AdminRole{}).BatchChange(datas).Error
				if err != nil {
					err = fmt.Errorf("排序失败！%v", err)
					return
				}
			}
			res.Reload = true
			return
		})
	ctrl.RenderForm(ctx, formBuilder)
}

// 下拉搜索可选项
func (ctrl *Role) DropdownSearchOptions(ctx *gin.Context) {
	options, err := roleservice.RolePage.DropdownSearchOptions(ctx)
	if err != nil {
		response.Fail(ctx, err.Error())
	} else {
		response.Success(ctx, options)
	}
}
